//
//  ToolsClass.m
//  YouChangCall
//
//  Created by app on 2016/11/29.
//  Copyright © 2016年 HZJiTeng. All rights reserved.
//

#import "ToolsClass.h"
//#import "LoginViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import <MediaPlayer/MediaPlayer.h>
#import "GWCodeLoginViewController.h"
#import "GWBaseNavigationController+GWGetCurrentNAV.h"

@implementation ToolsClass
static AFHTTPSessionManager *manager;
#pragma mark -- MD5加密(32位小写)

+ (NSString *)stringToMD5:(NSString *)str{
    //1.首先将字符串转换成UTF-8编码, 因为MD5加密是基于C语言的,所以要先把字符串转化成C语言的字符串
    const char *fooData = [str UTF8String];
    
    //2.然后创建一个字符串数组,接收MD5的值
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    
    //3.计算MD5的值, 这是官方封装好的加密方法:把我们输入的字符串转换成16进制的32位数,然后存储到result中
    CC_MD5(fooData, (CC_LONG)strlen(fooData), result);
    /**
     第一个参数:要加密的字符串
     第二个参数: 获取要加密字符串的长度
     第三个参数: 接收结果的数组
     */
    
    //4.创建一个字符串保存加密结果
    NSMutableString *saveResult = [NSMutableString string];
    
    //5.从result 数组中获取加密结果并放到 saveResult中
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [saveResult appendFormat:@"%02x", result[i]];
    }
    /*
     x表示十六进制，%02X  意思是不足两位将用0补齐，如果多余两位则不影响
     JTDLog("%02X", 0x888);  //888
     JTDLog("%02X", 0x4); //04
     */
    return saveResult;
}

#pragma mark -- 颜色转图片
+ (UIImage*)createImageWithColor:(UIColor*)color {
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

#pragma mark -- 生成随机字符串
+ (NSString *)getRandomStringWithLength:(NSInteger)length {
//    NSString *str = @"abcdefghijklmnopqrstuvwxyz0123456789";
    NSString *str = @"01234567890123456789";
    NSString *newStr = [NSString string];
    for (NSInteger i = 0; i < length; i++) {
        NSString *word = [str substringWithRange:NSMakeRange(arc4random()%str.length, 1)];
        newStr = [NSString stringWithFormat:@"%@%@",newStr,word];
    }
    return newStr;
}



#pragma mark -- 提示框
+(void)showTipsWithInfo:(NSString*)infoStr {
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    UIView*tipsView = [[UIView alloc]init];
    tipsView.bounds = CGRectMake(0, 0, 1, 1);
    tipsView.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2, [UIScreen mainScreen].bounds.size.height/2);
    tipsView.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:1];
    tipsView.clipsToBounds = YES;
    tipsView.alpha = 0;
    tipsView.tag = 987654321;
    tipsView.layer.cornerRadius = 8;
    [window addSubview:tipsView];
    [UIView animateWithDuration:0.25 animations:^{
        tipsView.bounds = CGRectMake(0, 0, 120, 80);
        tipsView.alpha = 0.8;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.05 animations:^{
            tipsView.bounds = CGRectMake(0, 0, 120, 80);
        } completion:^(BOOL finished) {
            UILabel*lab = [[UILabel alloc]init];
            lab.frame = CGRectMake(0, 0, 120, 80);
            lab.textAlignment = NSTextAlignmentCenter;
            lab.text = infoStr;
            lab.numberOfLines = 0;
            lab.textColor = [UIColor whiteColor];
            lab.font = [UIFont systemFontOfSize:15];
            [tipsView addSubview:lab];
            [UIView animateWithDuration:0.8 animations:^{
                tipsView.alpha = 0.81;
            } completion:^(BOOL finished) {
                [lab removeFromSuperview];
                [UIView animateWithDuration:0.3 animations:^{
                    tipsView.bounds = CGRectMake(0, 0, 1, 1);
                } completion:^(BOOL finished) {
                    [tipsView removeFromSuperview];
                }];
            }];
        }];
    }];
}

+ (void)showLongTipsWithInfo:(NSString*)infoStr {
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    UIView*tipsView = [[UIView alloc]init];
    tipsView.bounds = CGRectMake(0, 0, 1, 1);
    tipsView.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2, [UIScreen mainScreen].bounds.size.height/2);
    tipsView.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:1];
    tipsView.clipsToBounds = YES;
    tipsView.alpha = 0;
    tipsView.tag = 123456789;
    tipsView.layer.cornerRadius = 8;
    [window addSubview:tipsView];
    window.userInteractionEnabled = NO;
    [UIView animateWithDuration:0.25 animations:^{
        tipsView.bounds = CGRectMake(0, 0, 240, 80);
        tipsView.alpha = 0.8;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.05 animations:^{
            tipsView.bounds = CGRectMake(0, 0, 240, 80);
        } completion:^(BOOL finished) {
            UILabel*lab = [[UILabel alloc]init];
            lab.frame = CGRectMake(6, 0, 228, 80);
            lab.textAlignment = NSTextAlignmentCenter;
            lab.text = infoStr;
            lab.numberOfLines = 0;
            lab.textColor = [UIColor whiteColor];
            lab.font = [UIFont systemFontOfSize:15];
            [tipsView addSubview:lab];
            [UIView animateWithDuration:1.86 animations:^{
                tipsView.alpha = 0.81;
            } completion:^(BOOL finished) {
                window.userInteractionEnabled = YES;
                [lab removeFromSuperview];
                [UIView animateWithDuration:0.3 animations:^{
                    tipsView.bounds = CGRectMake(0, 0, 1, 1);
                } completion:^(BOOL finished) {
                    [tipsView removeFromSuperview];
                }];
            }];
        }];
    }];
}

+(void)showTipsWithActivityAlertInfo:(NSString*)infoStr {
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    UIView*tipsView = [[UIView alloc]init];
    tipsView.frame = CGRectMake(SCREEN_WIDTH/2, SCREEN_HEIGHT - TABBAR_HEIGHT -60, 1, 1);
//    tipsView.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2, SCREEN_HEIGHT - TABBAR_HEIGHT -30);
    tipsView.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:1];
    tipsView.clipsToBounds = YES;
    tipsView.alpha = 0;
    tipsView.tag = 98765;
    tipsView.layer.cornerRadius = 8;
    [window addSubview:tipsView];
    [UIView animateWithDuration:0.25 animations:^{
        tipsView.frame = CGRectMake(40, SCREEN_HEIGHT - TABBAR_HEIGHT -60,  SCREEN_WIDTH - 80, 40);
        tipsView.alpha = 0.8;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.05 animations:^{
            tipsView.frame = CGRectMake(40, SCREEN_HEIGHT - TABBAR_HEIGHT -60,  SCREEN_WIDTH - 80, 40);
        } completion:^(BOOL finished) {
            UILabel*lab = [[UILabel alloc]init];
            lab.frame = CGRectMake(10, 0, SCREEN_WIDTH - 90, 40);
            lab.textAlignment = NSTextAlignmentCenter;
            lab.text = infoStr;
            lab.numberOfLines = 0;
            lab.textColor = [UIColor whiteColor];
            lab.font = [UIFont systemFontOfSize:15];
            [tipsView addSubview:lab];
            [UIView animateWithDuration:3 animations:^{
                tipsView.alpha = 0.81;
            } completion:^(BOOL finished) {
                [lab removeFromSuperview];
                [UIView animateWithDuration:0.3 animations:^{
                    tipsView.bounds = CGRectMake(0, 0, 1, 1);
                } completion:^(BOOL finished) {
                    [tipsView removeFromSuperview];
                }];
            }];
        }];
    }];
}


#pragma mark --字典转json字符串方法
+ (NSString *)convertToJsonData:(NSDictionary *)dict {
    if (IsArrOrDicEmpty(dict)) {
        return @"";
    }
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        JTDLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}

+ (NSString *)jsonStringWithDict:(NSDictionary *)dict {
    NSError *error;
    
    // 注
    //NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingSortedKeys error:&error];
    
    // NSJSONWritingSortedKeys这个枚举类型只适用iOS11所以我是使用下面写法解决的
    if (@available(iOS 11.0, *)) {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingSortedKeys error:&error];
        
        if (!jsonData) {
            JTDLog(@"%@",error);
        }else{
            return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        }
    } else {
        return nil;
        // Fallback on earlier versions
    }
    return nil;
    
//    return jsonString;
}
#pragma mark --json转字典
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        JTDLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
+ (NSString *)newConvertToJsonData:(NSDictionary *)dict {
    NSError *error;
    //处理nsnumber number没有length参数
    NSMutableDictionary * newDict = [dict mutableCopy];
    for (NSString * key in dict) {
        id obj = [dict objectForKey:key];
        if (![obj isKindOfClass:[NSString class]]) {
            [newDict setObject:[NSString stringWithFormat:@"%@",obj] forKey:key];
        }
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:newDict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        JTDLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }

    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range];
    NSArray * valuesArray = [mutStr componentsSeparatedByString:@"\""];
    NSMutableString * newResult = [NSMutableString string];
    NSMutableString * tempResult = [NSMutableString string];
    NSInteger tag = 0;
    //处理参数为空
    if (IsArrOrDicEmpty(dict)) {
        [tempResult appendFormat:@"{}"];
        return tempResult;
    }

    for (int i= 0; i < valuesArray.count; i++) {
        NSString * string = valuesArray[i];
        if ((i)%2 == 0){
            tag += 1;
            [newResult appendFormat:i == 0 ? @"{%@" : @"\"%@" ,tempResult];
            NSRange range = {0,tempResult.length};
            [tempResult deleteCharactersInRange:range];
        }else{
            [tempResult  appendFormat: i == (valuesArray.count - 2) ? @"%@\"}" : tag%2 == 0 ? @"%@\"," : @"%@\":",string];
        }
    }
    
    return newResult;
}





#pragma mark --同盾参数
+ (NSDictionary *)getOptionWithType {
    //    [dic setObject:@"kaiyuan" forKey:@"partnerCode"];//字符串 partnerCode
    //    [dic setObject:@"kaiyuan_ios" forKey:@"appName"];//字符串 添加同盾平台上注册的appName
    //    [dic setObject:@tapToClose forKey:@"tapToClose"];//bool值，请根据需求填@(true) / @(false)
    //    [dic setObject:@lang forKey:@"lang"];//字符串，按需求选择语言，1、简体中文，2、繁体中文，3、英文
    //    [dic setObject:@skipCaptcha forKey:@"skipCaptcha"];//bool值，请根据需求填@(true) / @(false)
    //文档：https://bastiontest.tongdun.cn/sphinx/doc/frontEndDoc.htm#
    ///语言lang 1:简体中文 2:繁体中文 3:英文
    NSString *lang = [NSString stringWithFormat:@"%@",@"1"];
    NSInteger type = arc4random() % 3;
    NSDictionary *optionDic = nil;
    switch (type) {
        case 0:{
            optionDic = @{@"appName":@"kaiyuan_ios",@"partnerCode":@"kaiyuanhotels",@"tapToClose":@(true),@"lang":lang};//正式
//            optionDic = @{@"appName":@"kaiyuan_ios",@"partnerCode":@"kaiyuan",@"tapToClose":@(true),@"lang":lang};//测试
            break;
        }
        case 1:{
            optionDic = @{@"appName":@"kaiyuan_ios",@"partnerCode":@"kaiyuanhotels",@"tapToClose":@(true),@"lang":lang};//正式
//            optionDic = @{@"appName":@"kaiyuan_ios",@"partnerCode":@"kaiyuan",@"tapToClose":@(true),@"lang":lang};//测试
            break;
        }
        case 2:{
            optionDic = @{@"appName":@"kaiyuan_ios",@"partnerCode":@"kaiyuanhotels",@"tapToClose":@(true),@"lang":lang};//正式
//            optionDic = @{@"appName":@"kaiyuan_ios",@"partnerCode":@"kaiyuan",@"tapToClose":@(true),@"lang":lang};//测试
            break;
        }
        default:
            break;
    }
    return optionDic;

}

#pragma mark -- 创建带请求头的post请求
/**
 urlStr:链接
 headDic:存放请求头的字典
 bodyDic:存放请求体的字典
 */
+ (void)createPostHeaderRequestWithURL:(NSString *)urlStr withHeadDictionary:(NSDictionary *)headDic withBodyDictionary:(NSDictionary *)bodyDic withBlock:(void(^)(id obj,BOOL success))block {
    if (IsArrOrDicEmpty(bodyDic)) {
        bodyDic = @{};
    }

    //签名规则参考 http://wiki.shands.com/index.php/Gw-api%E7%AD%BE%E5%90%8D%E8%A7%84%E5%88%99
    NSString *timestamp = [ToolsClass currentTimeStr];
    // 不转json用dic传给后台有换行符 转json有坑，去空格的时候会把参数里面的空格也去掉
//    NSString *bodyJson = [ToolsClass convertToJsonData:bodyDic];
    //不会去掉参数里的空格
//    NSString *bodyJson = [ToolsClass newConvertToJsonData:bodyDic];
    //上面的数组给转丢了 换成系统的
    NSData *data = [NSJSONSerialization dataWithJSONObject:bodyDic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *bodyJson = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    //md5
    NSString *md5Str = [NSString stringWithFormat:@"%@&%@&%@&%@",APPSecret,APPKey,bodyJson,timestamp];
//    JTDLog(@"md5Str=%@",md5Str);
    NSString *token = [ToolsClass stringToMD5:md5Str];
//    NSString *signStr = [NSString stringWithFormat:@"%@?appkey=%@&timestamp=%@&token=%@&v=%@",urlStr,APPKey,timestamp,token,[GWUserData sharedManager].randomStr];
    
    AFHTTPSessionManager *manager = [ToolsClass sharedHTTPSession];
    
    manager.requestSerializer.timeoutInterval = TIMEOUTINTERVALSECOND;
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"2.0" forHTTPHeaderField:@"shands"];   
    
    [manager.requestSerializer setValue:@"20003" forHTTPHeaderField:@"appkey"];
    [manager.requestSerializer setValue:timestamp forHTTPHeaderField:@"timestamp"];
    [manager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
    [manager.requestSerializer setValue:@"2" forHTTPHeaderField:@"v"];
    
    if (!IsStrEmpty([GWUserData sharedManager].loginToken)) {
        NSString *AuthorizationStr = [NSString stringWithFormat:@"Bearer %@",[GWUserData sharedManager].loginToken];
        [manager.requestSerializer setValue:AuthorizationStr forHTTPHeaderField:@"Authorization"];
    }
    //https://www.jianshu.com/p/1105ca1422e3 改动af源码 因为传入手动转成json会有error：The `parameters` argument is not valid JSON.
//    JTDLog(@"signStr=%@/%@",urlStr,bodyJson);
    [manager POST:urlStr parameters:bodyJson progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        JTDLog(@"url=%@---responseObject=%@",urlStr,responseObject);
        if ([responseObject[@"code"] integerValue] == 991 || [responseObject[@"code"] integerValue] == 992 || [responseObject[@"code"] integerValue] == 993 || [responseObject[@"code"] integerValue] ==995) {
            [self clearUserData];
            GWCodeLoginViewController * login = [[GWCodeLoginViewController alloc] init];
            UIViewController * VC = [self currentViewController];
//            JTDLog(@"当前显示的控制器%@",VC);
            //判断是否已经显示登录窗口，没有显示则push显示
            if (![[NSString stringWithUTF8String:object_getClassName(VC)] isEqual:[NSString stringWithUTF8String:object_getClassName(login)]])
            {
                [GWUser writeIsPresentView:YES];//模态
                GWBaseNavigationController * nav = [[GWBaseNavigationController alloc] initWithRootViewController:login];
                [VC presentViewController:nav animated:YES completion:nil];
                
            }
            [GWUser writeIsPresentView:YES];//模态
        }else{
            block(responseObject,YES);
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        JTDLog(@"%@",error);
        
        block(nil,NO);
    }];
}

#pragma mark - 创建请求单例类
+ (AFHTTPSessionManager *)sharedHTTPSession{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer.acceptableContentTypes =  [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];
//    https://blog.csdn.net/wang631106979/article/details/52243028||https://www.jianshu.com/p/2bfccfa7f87b
//    请求的数据格式，发送给服务器的格式
//    AFHTTPRequestSerializer            //二进制的数据格式 （默认的）
//    AFJSONRequestSerializer            //JSON
//    AFPropertyListRequestSerializer   //PList
//    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = TIMEOUTINTERVALSECOND;
    manager.securityPolicy = [AFSecurityPolicy defaultPolicy];
    manager.securityPolicy.allowInvalidCertificates = YES;//忽略https证书
    manager.securityPolicy.validatesDomainName = NO;//是否验证域名
    return manager;
}

#pragma mark -- 创建带有请求头的get请求
+ (void)createGetHeaderRequestWithURL:(NSString *)urlStr withHeadDictionary:(NSDictionary *)headDic withBlock:(void(^)(id obj,BOOL success))block {
    AFHTTPSessionManager *manager = [ToolsClass sharedHTTPSession];
    manager.requestSerializer.timeoutInterval = TIMEOUTINTERVALSECOND;
//    //以下user_id,phone,token,只要本地存在就添加到请求头中
//    if (!IsStrEmpty([GWUserData sharedManager].user_id)) {
//        [manager.requestSerializer setValue:[GWUserData sharedManager].user_id forHTTPHeaderField:@"USER_ID"];
//    }
//    if (!IsStrEmpty([GWUserData sharedManager].phone)) {
//        [manager.requestSerializer setValue:[GWUserData sharedManager].phone forHTTPHeaderField:@"PHONE"];
//    }
////    if (!IsStrEmpty([GWUserData sharedManager].token)) {
////        [manager.requestSerializer setValue:[GWUserData sharedManager].token forHTTPHeaderField:@"TOKEN"];
////    }
//    if (headDic != nil) {
//        NSArray *valueArray = headDic.allValues;
//        NSArray *keyArray = headDic.allKeys;
//        for (NSInteger i = 0; i < valueArray.count; i++) {
//            [manager.requestSerializer setValue:valueArray[i] forHTTPHeaderField:keyArray[i]];
//        }
//    }
    
    [manager GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        JTDLog(@"responseObject=%@",responseObject);
        block(responseObject,YES);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        block(nil,NO);
        JTDLog(@"%@",error);
        
    }];
}
#pragma mark -- 获取当前日期
+ (NSString *)getNowDate {
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
     NSString *currentTime = [formatter stringFromDate:[NSDate date]];
    return currentTime;
}

#pragma mark -- 获取当前时间戳（毫秒）
+ (NSString *)currentTimeStr {
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970]*1000;// *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}

#pragma mark -- 获取当前日期(毫秒)
+ (NSString *)getNowTimeTimestamp3 {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
    
    return timeSp;
}
#pragma mark -- 判断某一个时间是今天，昨天或其他
+ (NSString *)getDateStr:(NSString *)str {
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *currentTime = [formatter stringFromDate:[NSDate date]];
    
    NSMutableString *currentDay = [NSMutableString stringWithString:currentTime];
    NSString *cuDay = [currentDay substringWithRange:NSMakeRange(4, 4)];
    NSString *preDay = [str substringWithRange:NSMakeRange(4, 4)];
    if ([cuDay isEqualToString:preDay]) {
        NSString *hh = [str substringWithRange:NSMakeRange(8, 2)];
        NSString *mm = [str substringWithRange:NSMakeRange(10, 2)];
        return [NSString stringWithFormat:@"今天\n%@:%@",hh,mm];
    }else{
        NSString *str5 = [str substringWithRange:NSMakeRange(4, 1)];
        NSString *str7 = [str substringWithRange:NSMakeRange(6, 1)];
        NSString *hh = [str substringWithRange:NSMakeRange(8, 2)];
        NSString *mm = [str substringWithRange:NSMakeRange(10, 2)];
        NSString *sub5;
        NSString *sub7;
        if ([str5 isEqualToString:@"0"]) {
            sub5 = [str substringWithRange:NSMakeRange(5, 1)];
        }else{
            sub5 = [str substringWithRange:NSMakeRange(4, 2)];
        }
        if ([str7 isEqualToString:@"0"]) {
            sub7 = [str substringWithRange:NSMakeRange(7, 1)];
        }else{
            sub7 = [str substringWithRange:NSMakeRange(6, 2)];
        }
        
        NSString *timeStr = [NSString stringWithFormat:@"%@月%@日\n%@:%@",sub5,sub7,hh,mm];
        return timeStr;
    }
}


+ (nullable GWBaseNavigationController *)rootNavigationController {

    GWBaseViewController * rootViewController =(GWBaseViewController *)UIApplication.sharedApplication.keyWindow.rootViewController;
    if (rootViewController) {
        if ([rootViewController isKindOfClass:[GWBaseTableViewController class]]) {
            GWBaseNavigationController * nav = ((GWBaseTableViewController *)rootViewController).selectedViewController;
            return nav;
        }else if ([rootViewController isKindOfClass:[GWBaseNavigationController class]]) {
            return (GWBaseNavigationController *)rootViewController;
        }
    }
    return nil;
}
+ (void)cellCornerRadius:(CGFloat)cornerRadius withView:(UIView *)view withByRoundingCorners:(NSInteger)byRoundingCorners {
    
    /**
     UIRectCornerTopLeft     = 1 << 0,
     UIRectCornerTopRight    = 1 << 1,
     UIRectCornerBottomLeft  = 1 << 2,
     UIRectCornerBottomRight = 1 << 3,
     
     */
    NSInteger top;
    NSInteger bottom;
    if (byRoundingCorners == 0) {
        top = 0;
        bottom = 1;
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(cornerRadius, cornerRadius)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = view.bounds;
        maskLayer.path = maskPath.CGPath;
        view.layer.mask = maskLayer;
        
    }else {
        top = 2;
        bottom = 3;
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(cornerRadius, cornerRadius)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = view.bounds;
        maskLayer.path = maskPath.CGPath;
        view.layer.mask = maskLayer;
        
    }
    
}

#pragma mark -- 空白页面
+ (void)createWrongViewForFlowWaterWithView:(UIView *)view {
    UIImageView *imageView = [view viewWithTag:554433];
    if (!imageView) {
        imageView = [[UIImageView alloc]init];
        imageView.tag = 554433;
        UIImage *image = IMAGE_NAME(@"空白");
        imageView.image = image;
        [view addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(view);
            make.top.equalTo(view).offset(HEIGHT_CONSTARIN(60));
            make.size.mas_equalTo(CGSizeMake(WIDTH_CONSTARIN(210), HEIGHT_CONSTARIN(130)));
        }];
    }
}

#pragma mark -- 判断手机号是否合法
+ (BOOL)valiMobile:(NSString *)mobile{
    if (mobile.length != 11) {
        return NO;
    }else{
        NSString *pattern = @"^1+[23456789]+\\d{9}";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
        BOOL isMatch = [pred evaluateWithObject:mobile];
        if (isMatch) {
            return YES;
        }else{
            return NO;
        }
    }
}
#pragma mark -- 获取当前视图所在的控制器
+ (UIViewController *)viewControllerWithView:(UIView *)view {
    for (UIView* next = [view superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}

#pragma mark -- 获取缓存文件路径
+ (NSString *)getCachesPath{
    // 获取Caches目录路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask,YES);
    NSString *cachesDir = [paths objectAtIndex:0];
    //    NSString *filePath = [cachesDir stringByAppendingPathComponent:@"myCache"];
    return cachesDir;
}
#pragma mark -- 计算单个缓存文件大小
+ (long long)fileSizeAtPath:(NSString*)filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
#pragma mark -- 计算缓存
+ (float)getCacheSizeAtPath:(NSString*)folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];//从前向后枚举器
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [ToolsClass fileSizeAtPath:fileAbsolutePath];
    }
    JTDLog(@"folderSize ==== %lld",folderSize);
    return folderSize/(1024.0*1024.0);
}
#pragma mark -- 清除缓存
+ (void)clearCacheAtPath:(NSString *)path withBlock:(void(^)(BOOL))block{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            //如有需要，加入条件，过滤掉不想删除的文件
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
        block(YES);
    }
}

#pragma mark -- 获取index后的日期
+ (NSDate *)getDateWithIndex:(NSInteger)index{
    //    NSDate * date = [self getLocaleDate];
    
    NSString *current = [ToolsClass getCurrentTime];//获取本地时间
    //    NSDate *currentDate = [self getInternetDate];//获取网络时间
    NSDate *currentDate = [ToolsClass dateFromString:current];
    
    NSCalendar *gregorian = nil;
    if ([NSCalendar respondsToSelector:@selector(calendarWithIdentifier:)]) {
        gregorian = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    }else{
        gregorian = [NSCalendar currentCalendar];
    }
    
    NSDateComponents *components = [gregorian components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay ) fromDate:currentDate];
    
    [components setDay:([components day]+index)];
    
    NSCalendar * calendar = [NSCalendar currentCalendar];
    NSDate * dateCalendar = [calendar dateFromComponents:components];
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    NSString * str = [formatter stringFromDate:dateCalendar];
//    NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
    
    
    NSDate *resultDate = [ToolsClass dateFromString:str];
    
    return resultDate;
}

///获取本地时间
+ (NSString *)getCurrentTime {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // yyyy-MM-dd 可自定义，也可以换成 yyyy-MM-dd HH:MM:SS
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
    
}
/**
  将字符串转成NSDate类型
  @param dateString 时间类型的字符串 例如：2018-07-12
  @return date
*/
+ (NSDate *)dateFromString:(NSString *)dateString {
    NSDateFormatter *inputFormatter= [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *inputDate = [inputFormatter dateFromString:dateString];
    //inputDate或出现相差八小时问题，下面是解决相差八小时
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: inputDate];
    NSDate *localeDate = [inputDate dateByAddingTimeInterval: interval];
    return localeDate;
}

#pragma mark -- 获取一个日期几天前的日期
+ (NSString *)getDateWithDate:(NSString *)date withIndex:(NSInteger)index {
//    NSString *current = [ToolsClass getCurrentTime];//获取本地时间
//    //    NSDate *currentDate = [self getInternetDate];//获取网络时间
    NSDate *currentDate = [ToolsClass dateFromString:date];
    
    NSCalendar *gregorian = nil;
    if ([NSCalendar respondsToSelector:@selector(calendarWithIdentifier:)]) {
        gregorian = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    }else{
        gregorian = [NSCalendar currentCalendar];
    }
    
    NSDateComponents *components = [gregorian components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay ) fromDate:currentDate];
    
    [components setDay:([components day]+index)];
    
    NSCalendar * calendar = [NSCalendar currentCalendar];
    NSDate * dateCalendar = [calendar dateFromComponents:components];
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
//    formatter.dateFormat = @"yyyy-MM-dd";
    formatter.dateFormat = @"MM月dd日";
    NSString * str = [formatter stringFromDate:dateCalendar];
    //    NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
    
    
//    NSDate *resultDate = [ToolsClass dateFromString:str];
    
    return str;
}

#pragma mark -- 计算两个日期之间的天数
+ (NSInteger)calcDaysFromBegin:(NSDate *)beginDate end:(NSDate *)endDate{
    //创建日期格式化对象
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    //取两个日期对象的时间间隔：
    //这里的NSTimeInterval 并不是对象，是基本型，其实是double类型，是由c定义的:typedef double NSTimeInterval;
    NSTimeInterval time=[endDate timeIntervalSinceDate:beginDate];
    
    int days=((int)time)/(3600*24);
    //int hours=((int)time)%(3600*24)/3600;
    //NSString *dateContent=[[NSString alloc] initWithFormat:@"%i天%i小时",days,hours];
    return days;//结束时间那天还没到24点 就少一天，手动加一天
}
//获取日期是周几
+ (NSString *)calculateWeek:(NSDate *)date{
    NSCalendar *myCalendar = [NSCalendar currentCalendar];
    myCalendar.timeZone = [NSTimeZone systemTimeZone];
    NSInteger week = [[myCalendar components:NSCalendarUnitWeekday fromDate:date] weekday];
    NSDate * nowDate = [ToolsClass getDateWithIndex:0];
    NSInteger i = [ToolsClass compareDate:nowDate withDate:date];
    if (i == 0) {
        return @"今天";
    }
    JTDLog(@"week:%zd",week);
    switch (week) {
        case 1:
            return @"周日";
            break;
        case 2:
            return @"周一";
            break;
        case 3:
            return @"周二";
            break;
        case 4:
            return @"周三";
            break;
        case 5:
            return @"周四";
            break;
        case 6:
            return @"周五";
            break;
        case 7:
            return @"周六";
            break;
            
        default:
            break;
    }
    return @"";
}

#pragma mark-日期比较
+ (NSInteger )compareDate:(NSDate *)date01 withDate:(NSDate *)date02{
    NSInteger ci;
    NSComparisonResult result = [date01 compare:date02];
    switch (result)
    {
            //date02比date01大
        case NSOrderedAscending: ci=1; break;
            //date02比date01小
        case NSOrderedDescending: ci=-1; break;
            //date02=date01
        case NSOrderedSame: ci=0; break;
        default: NSLog(@"erorr dates %@, %@", date02, date01); break;
    }
    return ci;
}
#pragma mark-data转str
+ (NSString *)getDate:(NSDate *)date {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *strDate = [dateFormatter stringFromDate:date];
    return strDate;
}
#pragma mark-date转字符串 月-日
+ (NSString *)getDateMonthWithDay:(NSDate *)date {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM月dd日"];
    NSString *strDate = [dateFormatter stringFromDate:date];
    return strDate;
}

#pragma mark -- webView的request添加header
+ (NSURLRequest *)addHeaderForRequest:(NSURLRequest *)request {
    NSMutableURLRequest *newRequest = [request mutableCopy];
    [newRequest addValue:[[UIDevice currentDevice] name] forHTTPHeaderField:@"DEVICE_NAME"];
    if (!IsStrEmpty([GWUserData sharedManager].user_id)) {
        [newRequest addValue:[GWUserData sharedManager].user_id forHTTPHeaderField:@"USER_ID"];
    }
    if (!IsStrEmpty([GWUserData sharedManager].cid)) {
        [newRequest addValue:[GWUserData sharedManager].cid forHTTPHeaderField:@"CID"];
    }
    if (!IsStrEmpty([GWUserData sharedManager].phone)) {
        [newRequest setValue:[GWUserData sharedManager].phone forHTTPHeaderField:@"PHONE"];
    }
    
//    if (!IsStrEmpty([GWUserData sharedManager].token)) {
//        [newRequest setValue:[GWUserData sharedManager].token forHTTPHeaderField:@"TOKEN"];
//    }
    return newRequest;
}

//身份证正则
+ (BOOL)isIdentityCard:(NSString *)IDCardNumber {
    if (IDCardNumber.length <= 0) {
        return NO;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:IDCardNumber];
}

//获取Window当前显示的ViewController
+ (UIViewController *)currentViewController {
    //获得当前活动窗口的根视图
    UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (1)
    {
        //根据不同的页面切换方式，逐步取得最上层的viewController
        if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = ((UITabBarController*)vc).selectedViewController;
        }
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController*)vc).visibleViewController;
        }
        if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        }else{
            break;
        }
    }
    return vc;
}
#pragma mark -- 创建显示错误信息的视图
+ (void)createWrongViewWithImage:(NSString *)imageName withTipsString:(NSString *)tips withView:(UIView *)view {
    UIImageView *imageView = [view viewWithTag:554433];
    if (!imageView) {
        imageView = [[UIImageView alloc]init];
        imageView.tag = 554433;
        imageView.alpha = 0.8;
        UIImage *image = IMAGE_NAME(imageName);
        imageView.image = image;
        [view addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(view);
            make.top.equalTo(view).offset(HEIGHT_CONSTARIN(100));
            make.size.mas_equalTo(CGSizeMake(HEIGHT_CONSTARIN(90), HEIGHT_CONSTARIN(60)));
        }];
    }
    UILabel *tipsLabel = [view viewWithTag:443322];
    if (!tipsLabel) {
        tipsLabel = [[UILabel alloc]init];
        tipsLabel.text = tips;
        tipsLabel.tag = 443322;
        tipsLabel.textColor = RGB(101, 101, 101);
        tipsLabel.font = FONT(14);
        tipsLabel.textAlignment = NSTextAlignmentCenter;
        [view addSubview:tipsLabel];
        [tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(imageView.mas_bottom).offset(HEIGHT_CONSTARIN(15));
            make.height.mas_equalTo(HEIGHT_CONSTARIN(16));
            make.centerX.equalTo(view);
            make.width.mas_equalTo(SCREEN_WIDTH/2.f);
        }];
    }
}


#pragma mark -- 将错误视图移除
+ (void)clearWrongViewWith:(UIView *)view {
    UIImageView *imageView = [view viewWithTag:554433];
    UILabel *label = [view viewWithTag:443322];
    if (imageView) {
        [imageView removeFromSuperview];
    }
    if (label) {
        [label removeFromSuperview];
    }
}
#pragma mark -- 顶部提示框
+ (void)showTopTopsView:(NSString *)tips withBOOL:(BOOL)index {
    TopTipsView *tipsView = [[TopTipsView alloc]initWithTips:tips withBOOL:index];
    tipsView.frame = CGRectMake(0, -STATUS_BAR_HEIGHT-44-20, SCREEN_WIDTH, STATUS_BAR_HEIGHT+44+20);
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    [window addSubview:tipsView];
    [window bringSubviewToFront:tipsView];
    [tipsView show];
}
#pragma mark -- 高度适配
+ (CGFloat)heightContains:(CGFloat)height {
    if (SCREEN_HEIGHT >= 812) { //如果是疯x就把头部的44剪掉之后再计算
        return (SCREEN_HEIGHT-56)/667.f*height;
    }else {
        return SCREEN_HEIGHT/667.f*height;
    }
}

#pragma mark -- 设置字体
+ (CGFloat)getFont:(CGFloat)font {
    //https://www.jianshu.com/p/8b8731ed84f8
    if (SCREEN_WIDTH == 320) {
//        return font -0.8;
        return font - 1.5;
    }else if (SCREEN_WIDTH == 375){
        return font;
//        return font -0.8;
    }else{
        return font +1.3;
    }

//    if (SCREEN_WIDTH == 375 || SCREEN_WIDTH > 414) {
//        return font;
//    }else {
//        return font - 1;
//    }
}

+ (CGFloat)getStringHeightWithText:(NSString *)text font:(UIFont *)font viewWidth:(CGFloat)width {

    // 设置文字属性 要和label的一致
    if (font == nil) {
        font = [UIFont fontWithName:@"Helvetica" size:18];
    }
    NSDictionary *attrs = @{NSFontAttributeName :font};
    
    CGSize maxSize = CGSizeMake(width, MAXFLOAT);
    
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    
    // 计算文字占据的宽高
    CGSize size = [text boundingRectWithSize:maxSize options:options attributes:attrs context:nil].size;
    
    // 当你是把获得的高度来布局控件的View的高度的时候.size转化为ceilf(size.height)。
    return  ceilf(size.height);
}
#pragma mark -- 将银行卡卡号前边的变成*，并且每四位添加空格，
+ (NSString *)getNewBankNumWitOldBankNum:(NSString *)bankNum {
    NSMutableString *mutableStr;
    if (bankNum.length) {
        mutableStr = [NSMutableString stringWithString:bankNum];
        for (int i = 0; i < mutableStr.length; i ++) {
            if (i<mutableStr.length - 4) {
                [mutableStr replaceCharactersInRange:NSMakeRange(i, 1) withString:@"*"];
            }
        }
        NSString *str = mutableStr;
        
        NSString *getString = @"";
        int a = (int)str.length/4;
        int b = (int)str.length%4;
        int c = a;
        if (b>0)
        {
            c = a+1;
        }
        else
        {
            c = a;
        }
        for (int i = 0 ; i<c; i++){
            NSString *string = @"";
            
            if (i == (c-1)){
                if (b>0){
                    string = [str substringWithRange:NSMakeRange(4*(c-1), b)];
                }else {
                    string = [str substringWithRange:NSMakeRange(4*i, 4)];
                }
                
            }
            else {
                string = [str substringWithRange:NSMakeRange(4*i, 4)];
            }
            getString = [NSString stringWithFormat:@"%@ %@",getString,string];
        }
        NSString *subString = [getString substringWithRange:NSMakeRange(0, 1)];
        if ([subString isEqualToString:@" "]) {
            NSString *resultStr = [getString substringFromIndex:1];
            return  resultStr;
        }
        
        return getString;
    }
    return @"";
    
}

//二维码生成
+ (UIImage *)qrImageWithString:(NSString *)string size:(CGSize)size color:(UIColor *)color backGroundColor:(UIColor *)backGroundColor
{
    CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    if (!qrFilter)
    {
        JTDLog(@"Error: Could not load filter");
        return nil;
    }
    
    [qrFilter setValue:@"H" forKey:@"inputCorrectionLevel"];
    
    
    NSData *stringData = [string dataUsingEncoding:NSUTF8StringEncoding];
    [qrFilter setValue:stringData forKey:@"inputMessage"];
    CIFilter * colorQRFilter = [CIFilter filterWithName:@"CIFalseColor"];
    [colorQRFilter setValue:qrFilter.outputImage forKey:@"inputImage"];
    //二维码颜色
    if (color == nil) {
        color = [UIColor blackColor];
    }
    if (backGroundColor == nil) {
        backGroundColor = [UIColor whiteColor];
    }
    [colorQRFilter setValue:[CIColor colorWithCGColor:color.CGColor] forKey:@"inputColor0"];
    //背景颜色
    [colorQRFilter setValue:[CIColor colorWithCGColor:backGroundColor.CGColor] forKey:@"inputColor1"];
    
    
    CIImage *outputImage = [colorQRFilter valueForKey:@"outputImage"];
    
    UIImage *smallImage = [self imageWithCIImage:outputImage orientation: UIImageOrientationUp];
    
    return [self resizeImageWithoutInterpolation:smallImage size:size];
}
+ (UIImage *)imageWithCIImage:(CIImage *)aCIImage orientation: (UIImageOrientation)anOrientation
{
    if (!aCIImage) return nil;
    
    CGImageRef imageRef = [[CIContext contextWithOptions:nil] createCGImage:aCIImage fromRect:aCIImage.extent];
    UIImage *image = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:anOrientation];
    CFRelease(imageRef);
    
    return image;
}
+ (UIImage *)resizeImageWithoutInterpolation:(UIImage *)sourceImage size:(CGSize)size
{
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    CGContextSetInterpolationQuality(UIGraphicsGetCurrentContext(), kCGInterpolationNone);
    [sourceImage drawInRect:(CGRect){.size = size}];
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result;
}

#pragma mark -- 退出登录，清除用户信息
+ (void)clearUserData{
    [GWUser writeIsLogin:NO];
    [GWUserData sharedManager].user_id = @"";
   
    [GWUserData sharedManager].phone = @"";
  
    [GWUserData sharedManager].loginToken = @"";
    [GWUser writeObject:[GWUserData sharedManager]];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"popHomePage" object:nil];


}

+ (void)textBlobk:(void (^)(NSString *str, id obj))block{
    
//    str =@"123";
}

@end
